<template>
  <div class="role-management-container">
   
    <!-- 搜索和操作区域 -->
    <div class="search-section">
      <div class="search-row">
        <div class="search-item">
          <label>角色名称:</label>
          <el-input
            v-model="searchForm.roleName"
            placeholder="请输入角色名称"
            clearable
            @keyup.enter="handleSearch"
          />
        </div>
        <div class="search-actions">
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </div>
      </div>
      <div class="action-row">
        <div class="right-actions">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增角色
          </el-button>
         
         
        </div>
      </div>
    </div>

    <!-- 角色列表 -->
    <div class="main-content">
      <div class="table-container">
        <el-table
          :data="roleList"
          v-loading="tableLoading"
          border
          stripe
          style="width: 100%"
        >
        
          <el-table-column prop="roleName" label="角色名称" width="150" />
          <el-table-column prop="roleCode" label="角色编码" width="150" />
         
          <el-table-column prop="status" label="状态" width="80">
            <template #default="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                {{ scope.row.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="addTime" label="创建时间" width="160" >
            <template #default="scope">
           
            {{ moment(scope.row.addTime).format("yyyy-MM-DD HH:mm:ss") }}
          </template>
          </el-table-column>
          <el-table-column label="操作" width="250" fixed="right">
            <template #default="scope">
              <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="small" type="warning" @click="handleAssignPermission(scope.row)">
                分配权限
              </el-button>
              <el-button 
                size="small" 
                :type="scope.row.status === 1 ? 'danger' : 'success'"
                @click="handleToggleStatus(scope.row)"
              >
                {{ scope.row.status === 1 ? '禁用' : '启用' }}
              </el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 新增/编辑角色对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleFormRules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="roleCode">
          <el-input v-model="roleForm.roleCode" placeholder="请输入角色编码" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input 
            v-model="roleForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入角色描述" 
          />
        </el-form-item>
      
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="roleForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="分配权限"
      width="700px"
    >
      <div class="permission-assignment">
        <p><strong>角色：</strong>{{ currentRole.roleName }}</p>
        <el-divider />
        <div class="permission-tree">
          <el-tree
            ref="permissionTreeRef"
            :key="permissionTreeKey"
            :data="permissionTree"
            :props="treeProps"
            show-checkbox
            node-key="id"
            :checked-keys="selectedPermissions"
            check-strictly
            @check="handlePermissionCheck"
          />
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPermissionAssignment">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, inject } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Download, Refresh } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import * as roleApi from '../../api/role'
import * as permissionApi from '../../api/permission'
import moment from 'moment'



interface Role {
  id: number
  roleName: string
  roleCode: string
  description: string
  remark?: string
  permissions?: Permission[]
  userCount?: number
  status: number
  addTime: string
  addProp:string
}

/**
 * 权限信息接口
 * 定义权限的基本信息结构
 */
interface Permission {
  id: number
  permissionName: string
  permissionCode: string
  permissionType: string
  parentId: number | null
  children?: Permission[]
}

/**
 * 搜索表单接口
 * 定义角色搜索的条件
 */
interface SearchForm {
  roleName: string
}

/**
 * 角色表单接口
 * 定义新增/编辑角色时的表单数据
 */
interface RoleForm {
  id?: number
  roleName: string
  roleCode: string
  description: string
  remark?: string
  status: number
  addProp:string
}

/**
 * 分页信息接口
 * 定义分页相关的参数
 */
interface Pagination {
  currentPage: number
  pageSize: number
  total: number
}

// ==================== 响应式数据 ====================
// 角色列表数据
const roleList = ref<Role[]>([])
// 权限树数据
const permissionTree = ref<Permission[]>([])
// 表格加载状态
const tableLoading = ref(false)
// 对话框显示状态
const dialogVisible = ref(false)
const permissionDialogVisible = ref(false)
// 对话框标题
const dialogTitle = ref('')
// 当前操作角色
const currentRole = ref<Role>({} as Role)
// 选中的权限
const selectedPermissions = ref<number[]>([])
// 权限树key，用于强制重新渲染
const permissionTreeKey = ref(0)

// 搜索表单
const searchForm = reactive<SearchForm>({
  roleName: ''
})

// 角色表单
const roleForm = reactive<RoleForm>({
  roleName: '',
  roleCode: '',
  description: '',
  remark: '',
  status: 1,
  addProp:""
})

// 分页信息
const pagination = reactive<Pagination>({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表单引用
const roleFormRef = ref<FormInstance>()
const permissionTreeRef = ref()

// 注入菜单刷新方法
const refreshMenu = inject<() => void>('refreshMenu')

// 树形组件属性
const treeProps = {
  children: 'children',
  label: 'permissionName'
}

// ==================== 表单验证规则 ====================
/**
 * 角色表单验证规则
 * 定义各个字段的验证条件
 */
const roleFormRules: FormRules = {
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '角色名称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  roleCode: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
  
  ],
  description: [
    { required: true, message: '请输入角色描述', trigger: 'blur' }
  ]
}

// ==================== 生命周期钩子 ====================
/**
 * 组件挂载时初始化数据
 * 加载角色列表和权限树
 */
onMounted(() => {
  loadRoleList()
  loadPermissionTree()
})

// ==================== 数据加载方法 ====================
/**
 * 加载角色列表
 * 根据搜索条件和分页参数获取角色数据
 */
const loadRoleList = async () => {
  try {
    tableLoading.value = true
    const response = await roleApi.getRoleList({
      roleName: searchForm.roleName,
      page: pagination.currentPage,
      size: pagination.pageSize
    })
    
    if (response.data.code === 200) {
      roleList.value = response.data.data.list || []
      pagination.total = response.data.data.count || 0
    } else {
      ElMessage.error(response.data.message || '加载角色列表失败')
    }
  } catch (error: any) {
    ElMessage.error('加载角色列表失败')
    console.error('加载角色列表失败:', error)
  } finally {
    tableLoading.value = false
  }
}

/**
 * 加载权限树
 * 获取所有权限信息构建树形结构
 */
const loadPermissionTree = async () => {
  try {
    const response = await permissionApi.getPermissionTree()
    
    if (response.data.code === 200) {
      const rawData = response.data.data || []
      
      // 递归处理权限数据，确保字段名统一
      const processPermissionData = (items: any[]): any[] => {
        return items.map((item: any) => {
          const processedItem: {
            id: any;
            permissionName: any;
            permissionCode: any;
            permissionType: any;
            parentId: any;
            children: any[];
          } = {
            id: item.Id || item.id,
            permissionName: item.PermissionName || item.permissionName || item.name,
            permissionCode: item.PermissionCode || item.permissionCode || item.code,
            permissionType: item.PermissionType || item.permissionType || item.type,
            parentId: item.ParentId || item.parentId,
            children: []
          }
          
          // 递归处理子权限
          const children = item.Children || item.children || []
          if (children && children.length > 0) {
            processedItem.children = processPermissionData(children)
          }
          
          return processedItem
        })
      }
      
      permissionTree.value = processPermissionData(rawData)
      console.log('权限树数据:', permissionTree.value)
    } else {
      ElMessage.error(response.data.message || '加载权限树失败')
    }
  } catch (error: any) {
    ElMessage.error('加载权限树失败')
    console.error('加载权限树失败:', error)
  }
}

// ==================== 搜索和操作方法 ====================
/**
 * 执行搜索
 * 重置分页并重新加载数据
 */
const handleSearch = () => {
  pagination.currentPage = 1
  loadRoleList()
}

/**
 * 重置搜索条件
 * 清空搜索表单并重新加载数据
 */
const resetSearch = () => {
  searchForm.roleName = ''
  pagination.currentPage = 1
  loadRoleList()
}

/**
 * 刷新数据
 * 重新加载当前页面的数据
 */
const refreshData = () => {
  loadRoleList()
}

/**
 * 分页大小改变
 * 当用户改变每页显示数量时触发
 */
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  loadRoleList()
}

/**
 * 当前页改变
 * 当用户切换页码时触发
 */
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  loadRoleList()
}

// ==================== 角色操作方法 ====================
/**
 * 新增角色
 * 打开新增角色对话框
 */
const handleAdd = () => {
  dialogTitle.value = '新增角色'
  resetForm()
  dialogVisible.value = true
}

/**
 * 编辑角色
 * 打开编辑角色对话框并填充数据
 */
const handleEdit = (role: Role) => {
  dialogTitle.value = '编辑角色'
  Object.assign(roleForm, {
    id: role.id,
    roleName: role.roleName,
    roleCode: role.roleCode,
    description: role.description,
    remark: role.remark,
    status: role.status,
    addProp:localStorage.getItem("userNickname") || ''
  })
  dialogVisible.value = true
}

/**
 * 分配权限
 * 打开权限分配对话框
 */
const handleAssignPermission = async (role: Role) => {
  currentRole.value = role
  permissionDialogVisible.value = true
  
  // 先清空选中状态
  selectedPermissions.value = []
  
  try {
    // 确保权限树已加载
    if (permissionTree.value.length === 0) {
      await loadPermissionTree()
    }
    
    // 获取角色的权限数据
    const response = await roleApi.getRolePermissions(role.id)
    
    if (response.data.code === 200) {
      const rolePermissions = response.data.data || []
      // 提取权限ID列表
      const permissionIds = rolePermissions.map((p: any) => p.Id || p.id)
      
      console.log('角色权限数据:', rolePermissions)
      console.log('选中的权限ID:', permissionIds)
      
      // 使用 nextTick 确保 DOM 更新后再设置选中状态
      await nextTick()
      selectedPermissions.value = permissionIds
      
      // 更新权限树key强制重新渲染
      permissionTreeKey.value++
      
      // 等待一小段时间确保权限树完全渲染
      setTimeout(() => {
        if (permissionTreeRef.value) {
          permissionTreeRef.value.setCheckedKeys(permissionIds)
          console.log('手动设置权限树选中状态:', permissionIds)
        }
      }, 100)
    } else {
      ElMessage.error(response.data.message || '获取角色权限失败')
      selectedPermissions.value = []
    }
  } catch (error: any) {
    ElMessage.error('获取角色权限失败')
    console.error('获取角色权限失败:', error)
    selectedPermissions.value = []
  }
}

/**
 * 处理权限选择变化
 * 当用户勾选或取消勾选权限时触发
 */
const handlePermissionCheck = (data: any, checkedInfo: any) => {
  selectedPermissions.value = checkedInfo.checkedKeys
  console.log('权限选择变化:', checkedInfo.checkedKeys)
}

/**
 * 过滤节点方法
 * 用于权限树的搜索功能
 */
const filterNode = (value: string, data: any) => {
  if (!value) return true
  return data.permissionName.includes(value)
}

/**
 * 懒加载节点方法
 * 用于权限树的懒加载功能
 */
const loadNode = (node: any, resolve: any) => {
  // 这里可以实现懒加载逻辑
  resolve([])
}

/**
 * 允许拖拽方法
 * 用于权限树的拖拽功能
 */
const allowDrag = (node: any) => {
  return false // 不允许拖拽
}

/**
 * 允许放置方法
 * 用于权限树的拖拽功能
 */
const allowDrop = (draggingNode: any, dropNode: any, type: any) => {
  return false // 不允许放置
}

/**
 * 处理节点拖拽开始
 * 用于权限树的拖拽功能
 */
const handleNodeDragStart = (node: any, ev: any) => {
  console.log('节点拖拽开始:', node)
}

/**
 * 处理节点拖拽进入
 * 用于权限树的拖拽功能
 */
const handleNodeDragEnter = (draggingNode: any, dropNode: any, ev: any) => {
  console.log('节点拖拽进入:', draggingNode, dropNode)
}

/**
 * 处理节点拖拽离开
 * 用于权限树的拖拽功能
 */
const handleNodeDragLeave = (draggingNode: any, dropNode: any, ev: any) => {
  console.log('节点拖拽离开:', draggingNode, dropNode)
}

/**
 * 处理节点拖拽悬停
 * 用于权限树的拖拽功能
 */
const handleNodeDragOver = (draggingNode: any, dropNode: any, ev: any) => {
  console.log('节点拖拽悬停:', draggingNode, dropNode)
}

/**
 * 处理节点拖拽结束
 * 用于权限树的拖拽功能
 */
const handleNodeDragEnd = (draggingNode: any, dropNode: any, dropType: any, ev: any) => {
  console.log('节点拖拽结束:', draggingNode, dropNode, dropType)
}

/**
 * 处理节点放置
 * 用于权限树的拖拽功能
 */
const handleNodeDrop = (draggingNode: any, dropNode: any, dropType: any, ev: any) => {
  console.log('节点放置:', draggingNode, dropNode, dropType)
}

/**
 * 处理节点点击
 * 用于权限树的点击功能
 */
const handleNodeClick = (data: any, node: any, component: any) => {
  console.log('节点点击:', data, node)
}

/**
 * 处理节点右键菜单
 * 用于权限树的右键菜单功能
 */
const handleNodeContextmenu = (event: any, data: any, node: any, component: any) => {
  console.log('节点右键菜单:', event, data, node)
}

/**
 * 处理节点展开
 * 用于权限树的展开功能
 */
const handleNodeExpand = (data: any, node: any, component: any) => {
  console.log('节点展开:', data, node)
}

/**
 * 处理节点折叠
 * 用于权限树的折叠功能
 */
const handleNodeCollapse = (data: any, node: any, component: any) => {
  console.log('节点折叠:', data, node)
}

/**
 * 切换角色状态
 * 启用或禁用角色
 */
const handleToggleStatus = async (role: Role) => {
  const action = role.status === 1 ? '禁用' : '启用'
  try {
    await ElMessageBox.confirm(
      `确定要${action}角色 "${role.roleName}" 吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await roleApi.toggleRoleStatus(role.id, role.status === 1 ? 0 : 1)
    
    if (response.data.code === 200) {
      ElMessage.success(`${action}角色成功`)
      loadRoleList()
    } else {
      ElMessage.error(response.data.message || `${action}角色失败`)
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(`${action}角色失败`)
      console.error(`${action}角色失败:`, error)
    }
  }
}

/**
 * 删除角色
 * 删除指定角色
 */
const handleDelete = async (role: Role) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色 "${role.roleName}" 吗？此操作不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await roleApi.deleteRole(role.id)
    
    if (response.data.code === 200) {
      ElMessage.success('删除角色成功')
      loadRoleList()
    } else {
      ElMessage.error(response.data.message || '删除角色失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('删除角色失败')
      console.error('删除角色失败:', error)
    }
  }
}



// ==================== 表单处理方法 ====================
/**
 * 重置表单
 * 清空表单数据
 */
const resetForm = () => {
  Object.assign(roleForm, {
    id: undefined,
    roleName: '',
    roleCode: '',
    description: '',
    remark: '',
    status: 1
  })
  roleFormRef.value?.clearValidate()
}

/**
 * 提交表单
 * 验证表单并提交数据
 */
const submitForm = async () => {
  if (!roleFormRef.value) return
  
  try {
    await roleFormRef.value.validate()
    
    let response
    if (roleForm.id) {
    
      response = await roleApi.updateRole(roleForm)
    
    } else {
      roleForm.addProp=localStorage.getItem("userNickname") || ''

      response = await roleApi.createRole(roleForm)
    
    
    }
    
    if (response.data.code === 200) {
      ElMessage.success(roleForm.id ? '更新角色成功' : '创建角色成功')
      dialogVisible.value = false
      loadRoleList()
    } else {
      ElMessage.error(response.data.message || '保存角色失败')
    }
  } catch (error: any) {
    ElMessage.error('保存角色失败')
    console.error('保存角色失败:', error)
  }
}

/**
 * 提交权限分配
 * 保存角色的权限分配
 */
const submitPermissionAssignment = async () => {
  try {
    console.log('提交权限分配，选中的权限ID:', selectedPermissions.value)
    console.log('当前角色ID:', currentRole.value.id)
    
    const requestData = {
      roleId: currentRole.value.id,
      permissionIds: selectedPermissions.value
    }
    console.log('发送的请求数据:', requestData)
    
    const response = await roleApi.assignRolePermissions(requestData)
    
    console.log('API响应:', response)
    console.log('响应状态码:', response.data.code)
    console.log('响应消息:', response.data.message)
    
    if (response.data.code === 200) {
      ElMessage.success('分配权限成功')
      permissionDialogVisible.value = false
      loadRoleList()
      // 自动刷新菜单
      if (refreshMenu) {
        refreshMenu()
      }
    } else {
      ElMessage.error(response.data.message || '分配权限失败')
      console.error('分配权限失败，响应:', response.data)
    }
  } catch (error: any) {
    ElMessage.error('分配权限失败')
    console.error('分配权限失败:', error)
    console.error('错误详情:', error.response?.data)
  }
}
</script>

<style scoped>
.role-management-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 24px;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.search-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.search-row {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 15px;
}

.search-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.search-item label {
  white-space: nowrap;
  font-weight: 500;
}

.search-actions {
  margin-left: auto;
}

.action-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.right-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.refresh-icon {
  cursor: pointer;
  font-size: 18px;
  color: #666;
  transition: color 0.3s;
}

.refresh-icon:hover {
  color: #409eff;
}

.main-content {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.table-container {
  padding: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}

.permission-assignment {
  padding: 10px 0;
}

.permission-tree {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
}
</style>
